package com.yyaccp.itrip.utils;

import com.alibaba.fastjson.JSONObject;
import com.yyaccp.itrip.beans.domain.ItripUser;
import com.yyaccp.itrip.beans.vo.TokenVo;

/**
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/11/16.
 */
public class TokenUtil {
    private RedisAPI redisAPI;

    public void setRedisAPI(RedisAPI redisAPI) {
        this.redisAPI = redisAPI;
    }

    public TokenVo createToken(ItripUser user, String userAgent) {
        StringBuffer buffer = new StringBuffer();
        if(UserAgentUtil.isPc(userAgent)) {
            buffer.append("token:PC-");
        } else {
            buffer.append("token:mobile-");
        }
        buffer.append(MD5.md5(user.getUserCode()));
        buffer.append("-").append(user.getId());
        buffer.append("-").append(System.currentTimeMillis());
        buffer.append("-").append(MD5.md5(userAgent).substring(0, 6));
        TokenVo tokenVo = new TokenVo();
        tokenVo.setToken(buffer.toString());
        tokenVo.setGenTime(System.currentTimeMillis());
        if(UserAgentUtil.isPc(userAgent)) {
            tokenVo.setExpTime(System.currentTimeMillis() + 7200000);
            redisAPI.setex("token",7200, JSONObject.toJSONString(tokenVo));
        } else {
            redisAPI.set("token", JSONObject.toJSONString(tokenVo));
        }
        return tokenVo;
    }
}
